/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.common.util;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;

import java.security.Security;

/**
 * SM3Util 工具类
 *
 * @author Mark·虎克 (2486970363@qq.com)
 */
public class SM3Util {

    static {
        // 添加 Bouncy Castle 安全提供者
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    private SM3Util() {
        // 私有构造函数，防止实例化
    }

    /**
     * 计算输入数据的 SM3 哈希值
     *
     * @param data 输入的数据，以字节数组形式表示
     * @return 十六进制字符串形式的 SM3 哈希值
     */
    public static String hash(byte[] data) {
        // 创建 SM3 摘要对象
        SM3Digest digest = new SM3Digest();
        // 更新摘要对象的输入数据
        digest.update(data, 0, data.length);
        // 存储最终的哈希结果
        byte[] hash = new byte[digest.getDigestSize()];
        // 完成哈希计算
        digest.doFinal(hash, 0);
        // 将字节数组形式的哈希结果转换为十六进制字符串
        return Hex.toHexString(hash);
    }

    /**
     * 计算输入字符串的 SM3 哈希值
     *
     * @param data 输入的字符串
     * @return 十六进制字符串形式的 SM3 哈希值
     */
    public static String hash(String data) {
        // 将字符串转换为字节数组，使用 UTF-8 编码
        return hash(data.getBytes());
    }
}